/* 
    Document   : main
    Created on : Dec 14, 2013, 4:00:40 PM
    Author     : Evgeniy Grigorevskiy
    Description:
        Purpose of the stylesheet follows.
 */

var $j = jQuery.noConflict();

/*before loading page*/
$j(document).ready(function(){
    var servletUrl = "Controller";
    $j.post(servletUrl, {
        type: "onload"  
    }, function (data){
        alert('Test cookies and session: '+data);
    });
/* First - check browser version .. if it's IE 8- -> ask to update it to IE9+ or install Chrome/Safari/Mozilla/Opera
     * 
  -> * So here i have to send an information about loading page and get next instructions:
     * 1. What type of page must be loaded to this user
     * 2. FirstName of user to say Hello, Man! If this is a guest .. so null must be returned
     * 3. Content for 10 books
     * 
  -> * All this information come to me and i make next:
     * 0. Load context in anyway...
     * 1. If this is a guest - nothing change
     * 2. If this is not a guest -> change logout form and Local/Global library switcher and go to 3 paragraph
     * 3. Switch (role): case <T>: load <T> top-menu; break; default: send to ban user permanently =)
     */
});

$j(document).ready(function(){
    
    
    /*Here all functional for all elements of the page let's start =)*/

    // ------->      
    /*variables with self-described name*/
    
    // Servlet-controller URL 
    var servletUrl = "Controller";
    // AJAX JSP page for html code migration
    var ajaxPage= "ajaxAll.jsp";
    // amount of books for displaying .. by default=10 for grid view
    var booksAmount=10;
    // number of current page .. by default 1-st page...
    var currentPage=1;
    
    // ------->       
    /*Functions witch was used more than 1 time*/
    
    // Universal function for displaying hide blocks
    function showHideBlock(nameOfHideBlock){
        $j(nameOfHideBlock).fadeIn();
    }
    // Universal function for hiding secret blocks=)
    function hideHideBlock(nameOfHideBlock){
        $j(nameOfHideBlock).fadeOut();
    }
    // Parsing books from JSON to html for displaying
    function bookParseJsonToHtml(bookJSON, libraryType){    //libraryType={"local", "global"};
        var libraryButton;
        if (libraryType=="local"){
            libraryButton="in progress";                            //in progress
        } else {
            libraryButton="in progress too"                         //in progress
        }
        var temporary="some html code"                              //in progress
        
        return temporary;
    }
    // Posting information for servlet-controller
    function postToServlet(whatType, params, callBackFunction){   //if no callback function - put "none"
        $j.post(servletUrl, {
            type: whatType,
            parameters: params
        }, function (data){
            alert('BackForDebbuging: '+data);
            if (callBackFunction=="none"){
                alert("No function to callback found")
                return data;
            } else {
                callBackFunction(data);
            }
        });
    }
    // 
    // Mb some helping functions (validation, cleaning fields and so on) witch make code more readable
    
    // clear input fields by an array of their names
    function clearInputs(names){    //use an array!!!
        for (i=0; i<names.length;i++){
            $j(names[i]).val("");
        }
    }
    
    // Function for checking registration fields...
    function checkInputsRegistration(){
        var error="E-mail is incorrect. Try again!";
        
        var lengthIncorrectForFirst2Fields=true, lengthIncorrectForLast2Fields=true;
        var passAndConfPassMissmatched=true, eMailIncorrect=true, tooShortPass=true;
        
        /*e-mail validation*/
        
        var reg = new RegExp("[0-9a-z_]+@[0-9a-z_^.]+\\.[a-z]{2,3}", 'i');
        if (!reg.test($j('#eMail').val())) {
            eMailIncorrect=false;
        }
        
        if ($j('#login').val().length <= 0 ||  $j('#firstName').val().length <= 0){
            lengthIncorrectForFirst2Fields=false;
            error="notAllFields";
        }
        if ($j('#lastName').val().length <= 0 || $j('#eMail').val().length <= 0){
            lengthIncorrectForLast2Fields=false;
            error="notAllFields";
        }
        
        if ($j('#password').val() != $j('#confirmPassword').val()){
            passAndConfPassMissmatched=false;
            error='password and confirmed password fields are missmatch!';
        }
        
        if ($j('#password').val().length <= 5){
            tooShortPass=false;
            error='Too short password';
        }
         
        checkInputsRegistration.getError= function(){
            return error;
        }
        var result= lengthIncorrectForFirst2Fields && lengthIncorrectForLast2Fields;
        result = result && passAndConfPassMissmatched && eMailIncorrect && tooShortPass;
        if (result){
            return true;
        } else {
            return false;
        }
    }
    
    //temporary gag
    function IP(){ 
        alert('In progress... It will work soon! Thanks for understanding and have a nice day=)');
    }
    //temporary for debugging
    function show(something){
        alert('Degub: '+something);
    }
    
    // ------->   
    /*Functions for elements on the page*/
    // Mb some funny actions on emblem's click =)
    
    //  -> Search for ISBN
    $j(document).on('click', '.imgSearchButton', function(){
        IP();
  
    /*if($j('#search').val().length>0){
            if (postToServlet("search",$j('#search').val(),"none")!="none"){
            //change content to bigList with this book 
            IP();
            } else {
                //haven't found this book
                alert('There is no book with this ISBN in DB');
            //offer: if it doesn't find than we should show adding book window with this ISBN =)
            }
        }*/
        
    });
    $j(document).on('keydown','#search', function(event){
        if (event.which == 13){
            IP();// some actions like sending to server information and so on
        /*if($j('#search').val().length>0){
                if (postToServlet("search",$j('#search').val(),"none")!="none"){
                    //change content to bigList with this book 
                    IP();
                } else {
                    //haven't found this book
                    alert('There is no book with this ISBN in DB');
                //offer: if it doesn't find than we should show adding book window with this ISBN =)
                }
            }*/
        }
    });
    // Registration - validation and posting to server information...
    
    
    $j(document).on('click', '#registrationButton', function(){
        showHideBlock('.registrationBlock');
        clearInputs(['#login','#password','#firstName','#lastName','#eMail','#confirmPassword']);
        $j('#login').focus();
    });
    //exit with Cancel button on form
    $j(document).on('click','#CancelRegistration',function(){
        hideHideBlock('.registrationBlock');
    });
    //exit with Esc button
    $j(document).on('keydown','.registrationBlock', function(event){
        if (event.which == 27){
            hideHideBlock('.registrationBlock');
        }
    });
    //exit with click on black form                                    in progress !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!1
    $j(document).on('click','.registrationBlock', function(){
        hideHideBlock('.registrationBlock');
    });
     
    $j(document).on('click','.registrationForm', function(event){
        //nothing happens if we click on white form for registration=) It must be so)   
        if (event.stopPropagation) {
            // For normal browsers...
            event.stopPropagation()
        } else {
            // For IE...
            event.cancelBubble = true
        }
    });
            
    $j(document).on('click', '#toCompleteRegistrationButton', function(){
        if (checkInputsRegistration()){
            var params= $j('#login').val()+";"+$j('#password').val()+";"+$j('#firstName').val()+";"+$j('#lastName').val()+";"+$j('#eMail').val();
            postToServlet("registration", params, show);
            hideHideBlock('.registrationBlock');
        } else {
            alert(checkInputsRegistration.getError());          
        }
    });
    
    $j(document).on('keydown','.registrationForm', function(event){
        if (event.which == 13){
            if (checkInputsRegistration()){
                var params = $j('#login').val()+";"+$j('#password').val()+";"+$j('#firstName').val();
                    params += ";"+$j('#lastName').val()+";"+$j('#eMail').val();
                postToServlet("registration", params, show);
                hideHideBlock('.registrationBlock');
            } else {
                alert(checkInputsRegistration.getError());          
            }
        }
    });
// Login
// Logout - mb redirect with deleting coockies and session .. and there is no troubles =)
// Search filters ... Mb try to connect it with ISBN search in some way...
// Adding book
// Publish book from local library to global
// Delete book from local library
// Profile actions -> for what ??? mb for vk users .. with asking them to edit their e-mail ...
// Books for publication: what will be if reject or publish ... 
// Reports: i don't remember what type of reports must be .. so I'll find out it later
// Ban user - ohoho =) Make a hide block for banning by e-mail or login user...
// If there is ban .. so unban must be too ...
// Pagination: previous and next pages .. displaying current page
// Footer information...
// 
//  -> Add book from global library to local
// Changing status of book in local library - finish combobox (or selectors)
// 
//  -> Admin's funny functional... Mb make another .jsp like: techSupport.jsp and make login page first... And one more JS
// 0. Login Banner first and don't display anything more
// 1. If all right - load admins page
// 2. Reports and ban functions, Deleting and approving publication some books to global library -> load from this script
// 3. Make unban users
// 4. Adding new users
// 5. Changing role of a user
// 6. Deleting users
// 7. Mailing users from our site
// 8. Mb some more functions ( witch I've missed or forgotten
//
    
    
/* Mmmm .. mb that's all ... Let's do the work! Good luck to us! =)*/
});




/*old scripts ... Will be deleted soon*/
$j(document).ready(function(){
    /*      Example of hidden block
$j('.signInButton').click(function(){
   $j('.over').fadeIn();
   $j('.inner').click(function(){//make close button and change inner to button close class
       $j('.over').fadeOut();
   });
});
     */
    
    
    
    /*---------------------Autorization and Registration------------------------*/
    /*Login with social site*/
    //check with DB and if true -> loading functional to user and changing block with ...
    var userName, pass, firstName, secondName, socialID, email, registrationDate;
    var servletUrl = "Controller";
    var googleBooksUrl = "GoogleBooks";
    var VkUrl="Vk";
    var userInfo;
    var bookInfo;
    
    
    
    function loadLoggedIn(someName){
        $j.get("ajaxAll.jsp", function(data) {
            data = $j(data);
            $j(".signIn").html($j('#logOut', data).html());
            // JS for loaded button
            $j('#logOutButton').click(function(){
                $j.get("ajaxAll.jsp", function(data) {
                    data = $j(data);
                    $j(".signIn").html($j('#loginBack', data).html());
                });
            });
            $j('.meetingUser').html('Hello, '+someName/*.firstName*/+'!');
        });
    }
    
    function servletDataExchange(whatType,mbsocialID, callback){
        $j.post(servletUrl, {
            type: whatType,
            socialID: mbsocialID
        }, function (data){
            alert('JSON: '+data);
            // userInfo=JSON.parse(data);
            userInfo=JSON.parse(data);
            alert('Name: '+userInfo.firstName);
            callback(userInfo);
        });
    }
    function checkAndGetUserInfo(login, pass, callback){
        $j.post(servletUrl, {
            type: "checknotsocial",
            userlog: login,
            userpass: pass
        }, function (data){
            alert('Result: '+data);
            if (data !="false"){
                //userInfo=JSON.parse(data);
                alert('Name: '+data);
                callback(data);
            //servletDataExchange("notsocial","",loadLoggedIn); 
            } else {
                alert ('Wrong Username or password! Try again');
                $j('#username').val("").focus();
                $j('#pass').val("");
            }
        });
    }
    $j(document).on('click', '#fb', function(){
        servletDataExchange("facebook","id100fb",loadLoggedIn);
    });
    $j(document).on('click', '#tw', function(){
        servletDataExchange("twitter","id200tw",loadLoggedIn);
    });
    
    $j(document).on('click', '#gPlus', function(){
        servletDataExchange("googlePlus","id400gP",loadLoggedIn);
    });
    
    /*Login with paragraphs in the form signIn*/

    $j(document).on('focusout', '#username', function(){// focus out from pass and userName -> Check string length -> printf Hi man
        userName = $j('#username').val();
        if(userName.length <= 0){ 
            alert('Enter your name');
        }
    });
    
    $j(document).on('focusout', '#pass', function(){
        pass = $j('#pass').val();
        if(pass.length <= 0){
            alert('Enter your pass');
        }
    });
    
    
    $j(document).on('click', '.signInButton', function(){
        if (userName.length>0 && pass.length>0){
            checkAndGetUserInfo(userName, pass,loadLoggedIn);
        }else{
            alert('Please, enter name and password!');
        }
    });
    

    /*---------------------Books Manipulation------------------------*/
    /****Adding Book****/
    $j(document).on('click', '#addBookButtonMain', function(){
        $j('.addBooksBlock').fadeIn();
        $j('#CancelBook').click(function(){//make close button and change inner to button close class
            $j('.addBooksBlock').fadeOut();
        });
        
    });
    
    function checkBooks(){
        /*ISBN = 10 symbols???*/
        var reg= new RegExp("[0-9]{10,13}");
        if (!reg.test($j('#ISBN').val()) || $j('#Title').val().length <=0 || $j('#Description').val().length <=0 || $j('#NumberOfPages').val().length <=0){
            return false;
        }
        return true;
    }
    
    $j(document).on('click', '#AddBook', function(){
        $j.post(googleBooksUrl, {
            isbn: $j('#ISBN').val()
        }, function (notParsedRecvObject){
            alert(notParsedRecvObject);
            var recvObject= JSON.parse (notParsedRecvObject);
            alert("JSON: isbn = "+recvObject.items[0].volumeInfo.industryIdentifiers[1].identifier +";\n\
                title "+ recvObject.items[0].volumeInfo.title+ "; \n\ author" +recvObject.items[0].volumeInfo.authors +";\n\
                description"+recvObject.items[0].volumeInfo.description+"; pages = "+ recvObject.items[0].volumeInfo.pageCount+";\n\
                image link = "+recvObject.items[0].volumeInfo.imageLinks.thumbnail);
            $j.post(servletUrl, {
                type : "addingNewBook",
                isbn : recvObject.items[0].volumeInfo.industryIdentifiers[1].identifier,
                title : recvObject.items[0].volumeInfo.title,
                authors : recvObject.items[0].volumeInfo.authors,
                description : recvObject.items[0].volumeInfo.description,
                numberOfPages : recvObject.items[0].volumeInfo.pageCount,
                image : recvObject.items[0].volumeInfo.imageLinks.thumbnail
            }, function (data){
                alert(data);
            });
        });
    });

    /***Change Books View***/
    var count=10;
    $j(document).on('click', '#gridButton', function(){
        $j('#content').attr('class','');
        $j('#content').addClass('grid');
        count=10;
    });
    $j(document).on('click', '#smallListButton', function(){
        $j('#content').attr('class','');
        $j('#content').addClass('smallList');
        count=20;
    });
    $j(document).on('click', '#bigListButton', function(){
        $j('#content').attr('class','');
        $j('#content').addClass('bigList');
        count=10;
    });
    
    var bookAmount = $j('.bookDisplay').size();
    var page = 1;    
        
    function displayParsedInfo(book){
        var temporary = "<div class='leftBookDisplay'> "
        +"<div class='image'><img src='"+book.image+"' /></div>" 
        +"<div class='rating'><h4>"+book.rating+"</h4></div></div>"
        +"<div class='rightBookDisplay'>"
        +"<div class='title'>"+book.title+"</div>"
        +"<div class='descp'>"+book.description+"</div>"
        +"<div class='isbn'>"+book.ISBN+"</div></div>";
        return temporary;
    }
    $j(document).on('click', '#left', function(){
        $j.post(servletUrl, {
            type: "previousBooks",
            pageNumber: page,
            amount: count
        }, function (data){
            var newPageBooks = data.split(';');
            var parsedBooks = new Array(newPageBooks.length);
            $j('#contentWrapper').html("");
            for(var i = 0;i < newPageBooks.length; i++){
                parsedBooks[i] = JSON.parse(newPageBooks[i]);
                $j('#contentWrapper').append('<div class="bookDisplay">' + displayParsedInfo(parsedBooks[i]) + '</div>');
            }
        });
    });  
    
    $j(document).on('click', '#localLibraryActive', function(){
        $j('#localLibraryActive').attr('class','');
        $j('#localLibraryActive').addClass('localLibraryActive');
        $j('#globalLibraryActive').attr('class','');
        count=20;
    });
    $j(document).on('click', '#globalLibraryActive', function(){
        $j('#globalLibraryActive').attr('class','');
        $j('#globalLibraryActive').addClass('globalLibraryActive');
        $j('#localLibraryActive').attr('class','');
        count=10;
    });
    
});//after page was loaded
